package com.css.zfzx.sjcj.modules.hddcDrillHole.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.repository.entity.HddcB3DrillprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB3DrillProjectTable.service.HddcB3DrillprojecttableService;
import com.css.zfzx.sjcj.modules.hddcDrillHole.repository.HddcDrillholeNativeRepository;
import com.css.zfzx.sjcj.modules.hddcDrillHole.repository.HddcDrillholeRepository;
import com.css.zfzx.sjcj.modules.hddcDrillHole.repository.entity.HddcDrillholeEntity;
import com.css.zfzx.sjcj.modules.hddcDrillHole.service.HddcDrillholeService;
import com.css.zfzx.sjcj.modules.hddcDrillHole.viewobjects.HddcDrillholeQueryParams;
import com.css.zfzx.sjcj.modules.hddcDrillHole.viewobjects.HddcDrillholeVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.repository.entity.HddcDrillprofileEntity;
import com.css.zfzx.sjcj.modules.hddcDrillProfile.service.HddcDrillprofileService;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.entity.HddcSamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.service.HddcSamplepointService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcDrillholeServiceImpl implements HddcDrillholeService {

	@Autowired
    private HddcDrillholeRepository hddcDrillholeRepository;
    @Autowired
    private HddcDrillholeNativeRepository hddcDrillholeNativeRepository;
    @Autowired
    private HddcSamplepointService hddcSamplepointService;
    @Autowired
    private HddcB3DrillprojecttableService hddcB3DrillprojecttableService;

    @Override
    public JSONObject queryHddcDrillholes(HddcDrillholeQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcDrillholeEntity> hddcDrillholePage = this.hddcDrillholeNativeRepository.queryHddcDrillholes(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcDrillholePage);
        return jsonObject;
    }


    @Override
    public HddcDrillholeEntity getHddcDrillhole(String id) {
        HddcDrillholeEntity hddcDrillhole = this.hddcDrillholeRepository.findById(id).orElse(null);
        return hddcDrillhole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillholeEntity saveHddcDrillhole(HddcDrillholeEntity hddcDrillhole) {
        String uuid = UUIDGenerator.getUUID();
        hddcDrillhole.setUuid(uuid);
        hddcDrillhole.setQualityinspectionStatus("0");
        hddcDrillhole.setCreateUser(PlatformSessionUtils.getUserId());
        hddcDrillhole.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcDrillhole.setIsValid("1");
        this.hddcDrillholeRepository.save(hddcDrillhole);
        return hddcDrillhole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillholeEntity updateHddcDrillhole(HddcDrillholeEntity hddcDrillhole) {
        UpdateUtil.copyNullProperties(hddcDrillholeRepository.findByUuidAndIsValid(hddcDrillhole.getUuid(), "1"), hddcDrillhole);
        hddcDrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcDrillhole.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcDrillholeRepository.save(hddcDrillhole);
        return hddcDrillhole;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcDrillholes(List<String> ids) {
        List<HddcDrillholeEntity> hddcDrillholeList = this.hddcDrillholeRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcDrillholeList) && hddcDrillholeList.size() > 0) {
            for (HddcDrillholeEntity hddcDrillhole : hddcDrillholeList) {
                hddcDrillhole.setIsValid("0");
                hddcDrillhole.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcDrillhole.setUpdateTime(new Date());
                this.hddcDrillholeRepository.save(hddcDrillhole);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcDrillholeQueryParams queryParams, HttpServletResponse response) {
        List<HddcDrillholeEntity> yhDisasterEntities = hddcDrillholeNativeRepository.exportYhDisasters(queryParams);
        List<HddcDrillholeVO> list = new ArrayList<>();
        for (HddcDrillholeEntity entity : yhDisasterEntities) {
            HddcDrillholeVO yhDisasterVO = new HddcDrillholeVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "钻孔-点", "钻孔-点", HddcDrillholeVO.class, "钻孔-点.xls", response);
    }

    @Override
    public HddcDrillholeEntity findById(String id) {
        HddcDrillholeEntity hddcDrillholeEntity = hddcDrillholeRepository.findbyId(id);
        return hddcDrillholeEntity;
    }

    @Override
    public List<HddcDrillholeEntity> findByProjectId(String id) {
        return hddcDrillholeRepository.findByProjectIdAndIsValid(id, "1");
    }

    @Autowired
    SuperRepository superRepository;

    //采样点
    @Transactional
    @Override
    public int pmdataQualityCheck() {
        List<HddcDrillholeEntity> listAll = hddcDrillholeRepository.findByAll();
        List<HddcDrillholeEntity> updateList = new ArrayList<>();
        //钻孔编号
        for (HddcDrillholeEntity b2All : listAll) {
            String str = "";
            if (StringUtils.isEmpty(b2All.getId())) {
                str += "【钻孔】钻孔编号为空。";
            } else {
                HddcSamplepointEntity hddcSamplepointEntity = hddcSamplepointService.findBySamplesourceid(b2All.getId());
                if (hddcSamplepointEntity == null) {
                    str += "【钻孔】表单中的钻孔编号与【采样点】中的钻孔编号不一致。";
                } else {
                    if (StringUtils.isEmpty(b2All.getFieldid())) {
                        str += "【钻孔】野外编号为空。";
                    } else {
                        if (!b2All.getFieldid().equals(hddcSamplepointEntity.getFieldid())) {
                            str += "【钻孔】表单中的野外编号与【采样点】中的野外编号不一致。";
                        }
                    }
                }
            }
            if (str.isEmpty()) {
                str += "【钻孔】与【采样点】质检成功";
                b2All.setQualityinspectionStatus("1");
            } else {
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcDrillholeVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcDrillholeVO.class, params);
            List<HddcDrillholeVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcDrillholeVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcDrillholeVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    public void saveDisasterList(List<HddcDrillholeVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcDrillholeEntity yhDisasterEntity = new HddcDrillholeEntity();
            HddcDrillholeVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcDrillhole(yhDisasterEntity);
        }
    }

}
